package cn.le.crawler;

import cn.le.enums.EnumCrawler;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description 简单的加锁,没有线程绑定,可能会被其它线程释放锁, 加锁线程异常时,会产生死锁
 * @Author le
 * @Date 2020/4/14 15:49
 * @Version 0.1
 **/
public class CrawlerLock {

    private static final Map<EnumCrawler, AtomicInteger> crawlerMap = new HashMap<>();

    public static void lock(EnumCrawler crawler){
        AtomicInteger integer = crawlerMap.get(crawler);
        if (integer == null) {
            synchronized (EnumCrawler.class) {
                    integer = new AtomicInteger(1);
                    crawlerMap.put(crawler, integer);
                return;
            }
        }
        if (integer.compareAndSet(0,1)){
            return;
        }else {
            throw new RuntimeException("正在爬取"+crawler.getText()+"房源，请稍等");
        }
    }

    public static void unlock(EnumCrawler crawler){
        AtomicInteger integer = crawlerMap.get(crawler);
        integer.compareAndSet(1,0);
    }
}
